﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Data;
using Scala.Logic;
using FluentNHibernate.Automapping;
using FluentNHibernate.Conventions.Helpers;
using NHibernate.Tool.hbm2ddl;
using NHibernate;
using NHibernate.Context;
using Scala.Data.Impl.Mappings;

namespace Scala.Data.Impl
{
    public class NhibernateConfigurator : IConfigurator
    {        
        ISessionFactory sessionFactory;

        public FluentConfiguration CreateSessionFactory()
        {
            try
            {
                return Fluently.Configure()
                    .Database 
                        (SQLiteConfiguration.Standard
                        .UsingFile(DAL.Default.DB_Filename)
                     .ShowSql()
                        )
                    .Mappings(m =>
                    {   
                        m.FluentMappings.AddFromAssemblyOf<NhibernateConfigurator>()
                            .Conventions.Add
                            (
                                DynamicInsert.AlwaysTrue(),
                                DynamicUpdate.AlwaysTrue()
                            )
                            .Conventions.Setup(c => 
                            {
                                c.Add<ColumnNullabilityConvention>();
                            });

                    })
                    
                    .ExposeConfiguration(cfg => 
                        { 
                             cfg.SetProperty("current_session_context_class", "call");
                            if(DAL.Default.Recreate_DB)
                                new SchemaExport(cfg).SetOutputFile("db.sql").Create(false, true);
                            else
                                new SchemaUpdate(cfg).Execute(false, true);
                        }
                   );
            }
            catch (Exception err)
            {
                throw new ApplicationException("Error during creation fluent session", err);
            }
        }


        public ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                    sessionFactory = CreateSessionFactory().BuildSessionFactory();
                return sessionFactory;              
            }
        }

        public ISession GetSession()
        {
            if (CurrentSessionContext.HasBind(SessionFactory))
                return SessionFactory.GetCurrentSession();

            throw new InvalidOperationException("Database access logic cannot be used, if session not opened.");
        }

       
    }
}
